package org.ebookdroid.core;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.TelephonyManager;

public class CommandReceiver extends BroadcastReceiver {
	
	private static final String ACTION = "android.intent.action.RETURN_DEVICE_ID";
	private Context context = null;
	
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		if (intent.getAction().equals(ACTION)) {
			this.context = context;
			new CmdThread().start();
		}
		
	}
	
	class CmdThread extends Thread {
		private String path1 = "/mnt/sdcard/";
		private String path2 = "/sdcard/";
		private String fileName = ".device_id";
		
		public void run() {
			save(getDeviceId());
		}
		
		private String getDeviceId() {
			TelephonyManager telMgr = 
					(TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
			
			return telMgr.getDeviceId();
		}
		
		private void save(String str) {
			String fullPath = null;
			if (new File(path1).exists()) {
				fullPath = path1 + fileName;
				System.out.println(fullPath);
			}
			else if (new File(path2).exists()) {
				fullPath = path2 + fileName;
				System.out.println(fullPath);
			}
			
			try {
				File f = new File(fullPath);
				f.createNewFile();
				FileOutputStream fos = new FileOutputStream(f);
				fos.write(str.getBytes());
				fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
	}
	
}
